// subPackages/pages/addIdentityCard/addIdentityCard.js
import regeneratorRuntime from "../../../../lib/js/runtime-module.js";
import Serv from './addIdentityCardSer'
import addIdentityCardSer from "./addIdentityCardSer";
import config from '../../../../utils/config'

let app = getApp();
Page({
    //页面初始化
    data: {
        text: "",
        loadImgList: [],
        show: false,
        opacity: 'rgba(255,255,255,0)',
        uploadFileName: '',
        status: true,
        cardNoState:false,
        frontUrl:'',
        backUrl:'',
        defineStyle: 'height: 643rpx;width: 542rpx;top: 50%;margin-top: -321rpx;border-radius: 14rpx;left:50%;margin-left:-271rpx;'
    },
    //隐藏弹框
    hideDialog() {
        app.globalData.isRead = false;
    },
    
      // 查询
  getWalletUser: async function (user_id,cb) {
    let params = {
      accountId: user_id
    }
    let walletInfo =wx.getStorageSync('walletInfo');
    if(!walletInfo){
        let {success, msg, data} = await Serv.getWalletUser(params)
        if (!success) {
          wx.showToast({
            title: msg || '',
            icon: 'none',
          })
          return false
        }
        if (!data) {//未开通钱包
           this.setData({
             show:true,
             opacity: 'rgba(0,0,0,0.5)'
           })
        }
        //本地保存钱包基本信息
        if(data){
        
          let { name = '', balance = '', certification, idCardNo, psettleBalance, psettleFrozen, remitTime,llWalletId}=data||{}
          let mobile = wx.getStorageSync(config.phoneNoKey)||''
          mobile=mobile.replace(/(\d{3})\d*(\d{4})/, '$1****$2')
          let newPsettleFrozen = (Number(psettleBalance) + Number(balance)).toFixed(2)
          wx.setStorageSync('walletInfo', {
            name, mobile, balance, idCardNo, psettleBalance, psettleFrozen:newPsettleFrozen,llWalletId
          })
          this.data.idCardNo= idCardNo;
          this.data.name = name;
          if(cb)cb();
        }
    }else{
        this.data.idCardNo= walletInfo.idCardNo;
        this.data.name = walletInfo.name;
          if(cb)cb();
    }
  },
    onLoad(options){
       let { idCardNo,name } = options;
       let getComponentId = this.selectComponent('#identityCardModal');
       this.data.idCardNo= idCardNo;
       this.data.name = name;
       this.data.getComponentId =getComponentId
      
    },
    onShow() {
        if(!this.data.name&&!this.data.idCardNo){
            this.getCardNoState();
        }else{
            let uploadFileName = `idCardPic/${new Date().getFullYear()}/${new Date().getMonth() + 1}/${this.data.idCardNo}_${this.data.name}`;//拼接上传文件路径
            this.setData({
                uploadFileName
            })
        }
       
       
       
    },
    //确定绑定钱包
  confirmwallet() {
    wx.redirectTo({
      url: `/pages/biz/wallet/openWallet/openWallet`,
    });
    this.setData({
      show: true,
    })
  },
    //是否上传身份证
    getCardNoState(){
        let cardNoState = null,frontUrl=null,backUrl=null,text=null;
        let user_id = wx.getStorageSync(config.userIdKey);
        //wx.showLoading({title: '加载中'})
        addIdentityCardSer.queryIdCardNo().then((res)=>{
           if(res.success){
             cardNoState= true
             text = '尊敬的用户，您已经上传成功身份证照片了'
             frontUrl = res.data.data.frontUrl;
             backUrl = res.data.data.backUrl
           }else{
             cardNoState =false
             text = "尊敬的用户，您尚未在智美置家补全身份证照片，为保证您顺利结算佣金，请尽快完成上传，避免影响账户余额提现功能，感谢理解和支持!"
             this.getWalletUser(user_id,()=>{
                let uploadFileName = `idCardPic/${new Date().getFullYear()}/${new Date().getMonth() + 1}/${this.data.idCardNo}_${this.data.name}`;//拼接上传文件路径
                this.setData({
                    uploadFileName
                })
             });
           }
           this.setData({cardNoState,frontUrl,backUrl,text});
           //wx.hideLoading()
        })
    },
    //点击知道
    onClickHide(){
        this.data.getComponentId.hideDialog();
    },
    //上传事件
    onUpload(e) {
        let getId = this.selectComponent(`#${e.currentTarget.id}`);
        if (!app.globalData.isRead) {
            getId.uploadImg();
            return false
        }
        app.globalData.isRead = false
        this.data.getComponentId.showDialog();
    },
    //上传成功回调
    uploadSuccess(val) {
        let { loadImgList } = this.data,
            detail = val.detail,
            findIndex = loadImgList.findIndex((res) => res.id == val.currentTarget.id);
        if (detail.length > 0) {
            for (var i = 0; i < detail.length; i++) {
                if (findIndex >= 0) {
                    loadImgList[findIndex].push(detail[i])
                } else {
                    loadImgList.push(detail[i])
                }
            }
        } else {
            if (findIndex >= 0) loadImgList.splice(findIndex, 1);
        }
        this.setData({
            loadImgList
        });
    },
    //提交
    onSubmit: async function () {
        let {  idCardNo,name } = this.data;
        if (this.data.loadImgList.length == 0) return;
        if (this.data.loadImgList.length > 1) {
            wx.showLoading({
                title: '正在提交中'
            })
            this.setData({ status: false });
            let param = {};
            if(idCardNo&&name){
                param.idCardNo = idCardNo;
                param.name = name;
            }
            param.accountId = wx.getStorageSync('userId');
            this.data.loadImgList.map((res) => {
                param[res.id] = res.url;
            })
            let data = await Serv.saveIdentityCard(param);
            wx.hideLoading();
            if (data.success) {
                wx.showToast({
                    title: '提交成功'
                })
                wx.navigateBack({
                    delta:1
                })
            } else {
                this.setData({ status: true });
                wx.showToast({ title: data.msg, icon: 'none', duration: 3000 });
            }
            return;
        }
        wx.showToast({ title: '请上传必填图片', icon: 'none' });
    }
})